<?php

namespace app\index\controller;

use app\common\IndexController;
use app\index\model\User as UserModel;
use app\index\model\Like;
use app\index\model\Category;
use app\index\model\Article;
use app\service\CosService;

class Campus extends IndexController
{
    //获取分类
    public function getCategory()
    {
        try {
            $category = new Category();
            $list = $category->getActiveCategories();
            return success('分类列表获取成功', $list);
        } catch (\Throwable $th) {
            return error('分类列表获取失败', $th->getMessage());
        }
    }

    //获取校园漫步文章列表
    public function getArticleList()
    {
        try {
            $page = input('page', 1);  // 获取页码，默认第1页
            $limit = input('limit', 10);  // 获取每页条数，默认10条

            $list = Article::where('article_status', 1)
                ->order('create_time', 'desc')
                ->paginate([
                    'list_rows' => $limit,
                    'page' => $page
                ]);

            return success('文章列表获取成功',  $list);
        } catch (\Throwable $th) {
            return error('文章列表获取失败', $th->getMessage());
        }
    }

    //获取文章详细页面
    public function getArticleDetail()
    {
        try {
            $id = $this->request->param('article_id');
            if (!$id) {
                return error('请先输入文章id');
            }
            $data = Article::where('article_id', $id)->find();
            //获取点赞状态
            $user_id = $this->userid;
            $likes = Like::getLikeInfo($id, $user_id);
            $res = array_merge($data->toArray(), $likes);
            return success('文章详情获取成功', $res);
        } catch (\Throwable $th) {
            return error('获取文章详情失败', $th->getMessage());
        }
    }

    //上传图片
    public function uploadImage()
    {
        try {
            $files = $this->request->file('file');

            if (empty($files)) {
                return error('请先选择图片');
            }

            if (!is_array($files)) {
                $files = [$files];
            }

            $cosService = new CosService();
            $urls = $cosService->uploadMultipleImages($files);

            return success('上传成功',  $urls);
        } catch (\Throwable $th) {
            return error('图片上传失败: ' . $th->getMessage());
        }
    }
    //删除图片
    public function deletedImage()
    {
        try {
            $urls = $this->request->param('urls');
            if (empty($urls)) {
                return error('请提供要删除的图片URL');
            }


            $cosService = new CosService();
            $res = $cosService->deleteImage($urls);
            return success('删除成功', $res);
        } catch (\Throwable $th) {
            return error('删除失败: ' . $th->getMessage());
        }
    }

    //点赞或取消点赞
    public function like()
    {
        try {
            $article_id = $this->request->param('article_id');
            $user_id = $this->userid;

            if (empty($article_id)) {
                return error('请先输入文章id');
            }

            $article = Article::where('article_id', $article_id)->find();
            $like = new Like();
            // 查找是否已经点赞
            $likeRecord = $like->where('article_id', $article_id)
                ->where('user_id', $user_id)
                ->find();

            if ($likeRecord) {
                // 已存在点赞记录，切换状态
                $newStatus = $likeRecord->status == 1 ? 0 : 1;
                $likeRecord->status = $newStatus;
                $likeRecord->save();

                // 更新文章点赞数
                if ($newStatus == 1) {
                    $article->setInc('article_likes');
                } else {
                    $article->setDec('article_likes');
                }

                $message = $newStatus == 1 ? '点赞成功' : '取消点赞成功';
            } else {
                // 创建新的点赞记录
                $like->save([
                    'user_id' => $user_id,
                    'article_id' => $article_id,
                    'status' => 1
                ]);

                // 更新文章点赞数
                $article->setInc('article_likes');
                $message = '点赞成功';
            }
            $likeCount = $like->where('article_id', $article_id)->where('status', 1)->count();
            $likeStatus = $like->where('article_id', $article_id)->where('user_id', $user_id)->value('status');
            $res = [
                'likeCounts' => $likeCount,
                'likeStatus' => $likeStatus
            ];
            return success($message, $res);
        } catch (\Throwable $th) {
            return error('点赞操作失败: ' . $th->getMessage());
        }
    }

    //发布文章
    public function addArticle()
    {
        try {
            $data = $this->request->param();

            if (empty($data['article_images']) || !is_array($data['article_images'])) {
                return json(['code' => 400, 'msg' => '请先选择图片']);
            }

            $userid = $this->userid;
            $userinfo = UserModel::field('id, nickname, avatar')->where('id', $userid)->find();
            $data['user_id'] = $userid;
            $data['user_nickname'] = $userinfo['nickname'];
            $data['user_avatar'] = $userinfo['avatar'];

            $data['article_images'] = json_encode($data['article_images'] ?? []);

            $article = new Article();
            $res = $article->save($data);
            return json(['code' => 200, 'msg' => '文章发布成功', 'data' => $res]);
        } catch (\Throwable $th) {
            return json(['code' => 500, 'msg' => '文章发布失败: ' . $th->getMessage()]);
        }
    }

    //搜索
    public function search()
    {
        $data = $this->request->param();
        $page = input('page', 1);  // 获取页码，默认第1页
        $limit = input('limit', 10);  // 获取每页条数，默认10条
        //模糊查询
        $list = Article::where('article_title', 'like', '%' . $data['search'] . '%')
            ->order('update_time', 'desc')
            ->paginate([
                'list_rows' => $limit,
                'page' => $page
            ]);
        return success('搜索成功', $list);
    }
}
